<template>
  <el-dialog
    class="troila-dialog"
    title="权限设置"
    :visible.sync="dialogFormVisible"
    :modal-append-to-body="true"
    :append-to-body="true"
    width="600px"
  >
    <el-form
      class="troila-form"
      :label-width="formLabelWidth"
      :model="form"
      :rules="rules"
      ref="form"
    >
      <el-form-item label="角色名称"
        ><div class="el-input">
          {{ ishasValue(form, 'roleName') }}
        </div>
      </el-form-item>
      <el-form-item label="功能权限" prop="menus">
        <div class="el-input__inner roleTree" v-loading="loading">
          <el-scrollbar v-if="list && list.length > 0">
            <el-tree
              @check="getCheck"
              :data="list"
              show-checkbox
              node-key="id"
              :default-expanded-keys="openKeys"
              :default-checked-keys="form.menus"
              check-strictly
              ref="tree"
              :props="{
                label: 'menuName',
              }"
            ></el-tree>
            <!-- expand-on-click-node 是否在点击节点的时候展开或者收缩节点 -->
            <!-- check-on-click-node 是否在点击节点的时候选中节点 -->
          </el-scrollbar>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="ajaxIng" @click="submitForm('form')"
        >确 定</el-button
      >
      <el-button @click="dialogFormVisible = false">{{
        ajaxIng ? '关 闭' : '取 消'
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  name: 'roleAuthority',
  props: {
    value: {
      // row
      type: [Boolean, Object],
      default: false,
    },
  },
  data() {
    return {
      dialogFormVisible: this.value ? true : false, //弹窗显示
      loading: false,
      ajaxIng: false,
      form: {
        roleName: '',
        menus: [],
      },
      formLabelWidth: '100px', //标题文字宽度
      rules: {
        menus: [{ required: true, message: '请选择菜单', trigger: 'change' }],
      },
      roleId: '',
      list: [],
    }
  },
  computed: {
    openKeys() {
      // console.log(this.list.map((v) => v.id))
      return this.list.map((v) => v.id)
    },
  },
  watch: {
    value(v) {
      let show = v ? true : false
      this.dialogFormVisible !== show ? (this.dialogFormVisible = show) : null
      if (v) {
        this.list = []
        this.roleId = v.id
        for (let k in this.form) {
          typeof this.form[k] == 'string' || typeof this.form[k] == 'number'
            ? (this.form[k] = v[k] || v[k] === 0 ? v[k] : '')
            : (this.form[k] = v[k] || v[k] === 0 ? [v[k]] : [])
        }
        this.form.menus = v.menuIdList
        this.getMenuList()
      }
    },
    dialogFormVisible(v) {
      v ? null : this.$emit('input', v)
    },
  },
  methods: {
    getMenuList() {
      this.loading = true
      this.API.menuManage
        .pageList({
          pageNum: 1,
          pageSize: 99999,
        })
        .then((res) => {
          this.loading = false
          if (res.code == 1) {
            this.list = this.toFilters(res.data.records)
            let list = []
            this.list.map((v) => {
              list = [...list, ...this.recursion(v)]
            })
            this.form.menus = this.form.menus.filter(
              (item) => list.indexOf(item) > -1
            )
          }
        })
        .catch((err) => {
          this.loading = false
        })
    },
    toFilters(list) {
      return list.filter((item) => {
        item.children && item.children.length > 0
          ? (item.children = this.toFilters(item.children))
          : null
        item.children.map((v) => {
          v.parent = item
        })
        return item.menuStatus != '0'
      })
    },
    getCheck(item, choose) {
      // console.log(
      //   item,
      //   choose,
      //   this.form.menus,
      //   this.$refs.tree.getCheckedNodes()
      // )
      let chooseItem = [...this.$refs.tree.getCheckedNodes()]
      let child = this.getChildren(item)
      let childKeys = child.map((v) => v.id)
      choose.checkedKeys.indexOf(item.id) > -1
        ? (chooseItem = chooseItem.concat(child))
        : (chooseItem = chooseItem.filter((v) => childKeys.indexOf(v.id) == -1))
      let chooseMenu = chooseItem.map((v) => v.id)
      if (chooseMenu.indexOf(item.id) > -1) {
        chooseMenu = chooseMenu.concat(this.getParents(item, chooseMenu))
      } else {
      }
      this.form.menus = [...chooseMenu]
      // this.form.menus.indexOf(item.id) > -1 &&
      // this.form.menus.indexOf(item.parentId) == -1
      //   ? this.form.menus.push(item.parentId)
      //   : null
      this.$refs.tree.setCheckedKeys(this.form.menus)
      // console.log(this.form.menus)
      this.$nextTick((v) => {
        this.$refs.form.validateField('menus')
      })
    },
    getParents(item, list) {
      let arr = []
      if (item.parentId != '0') {
        if (list.indexOf(item.parentId) == -1) {
          arr.push(item.parentId)
        }
        arr = [...arr, ...this.getParents(item.parent, list)]
      }
      return arr
    },
    getChildren(item) {
      let arr = []
      if (item.children && item.children.length > 0) {
        arr = [...item.children]
        for (let i in item.children) {
          arr = [...arr, ...this.getChildren(item.children[i])]
        }
      }
      return arr
    },
    submitForm(formName) {
      if (this.ajaxIng) {
        return
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            let postData = {
              id: this.roleId,
              menuId: this.form.menus.join(','),
            }
            this.API.roleManage.authority(postData).then((res) => {
              if (res.code == 1) {
                this.$alertFn.success(`操作成功 ！`)
                this.ajaxIng = false
                this.dialogFormVisible = false
                this.$emit('change')
              } else {
                this.$alertFn.error(`操作失败 ！`)
              }
            })
          } else {
            // console.log('error submit!!')
            return false
          }
        })
      }
    },
  },
}
</script>
<style scoped>
.roleTree {
  height: 300px !important;
  width: 360px;
  padding: 5px 0;
}
.roleTree > div {
  height: 100%;
}
</style>